precision mediump float;

uniform samplerCube u_s_texture;
uniform sampler2D u_texture_0;	//pool-floor texture (rock)
uniform sampler2D u_texture_1;	//normal map
uniform sampler2D u_texture_2;	//displacement map
uniform vec3 u_camera_pos;
uniform float u_time_2;

varying vec3 v_norm_world;
varying vec3 v_tangent_world;
varying vec3 v_binorm_world;
varying vec3 v_pos_world;
varying vec2 v_uv;


//Globals variables
vec3 normal_world;
float FresnelPower = 2.1;


void main()
{
	//depth = v_uv.x so it will gradually increase
	float depth = v_uv.x / 5.0;		// v_uv.x max is 5.0 (due to the .nfg file), so rescale it to 1.0

	//uv displacement
	float dMax = 0.086; //if dMax is greater, the fire will become more different to the original fire.
	vec2 disp = texture2D(u_texture_2, vec2(v_uv.x, v_uv.y + u_time_2)).rg;
	vec2 uv_disp_with_depth = v_uv + (2.0 * disp - 1.0) * (dMax * depth);

	// transform the normal from NormalMap (Texture space) to World space (also use displacement)
	vec3 normal = texture2D(u_texture_1, uv_disp_with_depth).xyz;
    mat3 TBN = mat3(normalize(v_tangent_world), normalize(v_binorm_world), normalize(v_norm_world));
    normal_world = normalize(TBN * (2.0 * normal - 1.0));
    
	// the color of water is reflected from sky
	vec3 toEye = normalize(u_camera_pos - v_pos_world);
	vec3 reflect = reflect(toEye, normal_world);
	vec4 Creflect = textureCube(u_s_texture, reflect);
	
	float f = pow((1.0 - abs(dot(normal_world, toEye))), FresnelPower);
	
	// the color of the water pool-floor (made of rock) being seen through water - refraction (also use displacement with depth)
	vec4 Crefract = texture2D(u_texture_0, uv_disp_with_depth / 2.0);	//scale the uv to make the rock bigger
	
	// the more the depth is, the more blue the water is
	Crefract = Crefract * (1.0 - depth) + vec4(0.25, 0.64, 0.87, 1.0) * depth;
	
	gl_FragColor = Crefract * (1.0 - f) + Creflect * f;
}